<template>
  <view class="container">
    <!-- 顶部状态 -->
    <view class="status-header">
      <view class="status-info">
        <view class="status-icon">
          <van-icon name="clock-o" color="#ff8c00" size="24" />
        </view>
        <text class="status-title">待支付</text>
      </view>
      <view class="countdown">
        <text class="countdown-label">剩余支付时间：</text>
        <text class="countdown-time">{{ formatTime(remainingTime) }}</text>
      </view>
    </view>

    <!-- 医院信息 -->
    <view class="hospital-header">
      <view class="hospital-logo">
        <image src="../../static/logo.png" class="avatar-image" />
      </view>
      <text class="hospital-name">{{ hospitalName }}</text>
      <van-icon name="arrow" color="#999" />
    </view>

    <!-- 预约信息卡片 -->
    <view class="appointment-card">
      <view class="appointment-main">
        <view class="date-section">
          <view class="date-number">{{ appointmentInfo.dayNumber }}</view>
          <view class="date-text">
            <text class="date-label">诊号</text>
          </view>
        </view>
        <view class="appointment-details">
          <view class="appointment-date">{{ appointmentInfo.fullDate }}</view>
          <view class="doctor-info">
            <text class="doctor-name">{{ appointmentInfo.doctorName }}</text>
            <text class="doctor-level">{{ appointmentInfo.doctorLevel }}</text>
          </view>
          <view class="time-slot">{{ appointmentInfo.timeSlot }}</view>
          <view class="department">{{ appointmentInfo.department }}</view>
        </view>
      </view>
    </view>

    <!-- 患者信息 -->
    <view class="patient-section">
      <view class="patient-info">
        <view class="patient-avatar">
          <image src="../../static/logo.png" class="avatar-image" />
        </view>
        <view class="patient-details">
          <text class="patient-name">{{ patientInfo.name }}</text>
          <text class="patient-basic">{{ patientInfo.gender }} {{ patientInfo.age }}岁 {{ patientInfo.phone }}</text>
        </view>
      </view>
      <view class="qr-code">
        <van-icon name="qr" size="24" color="#999" />
        <van-icon name="arrow" size="16" color="#999" />
      </view>
    </view>

    <!-- 预约信息详细列表 -->
    <view class="info-section">
      <view class="section-title">预约信息</view>
      <view class="info-list">
        <view class="info-item">
          <text class="info-label">就诊院区</text>
          <text class="info-value">{{ medicalStore.getCurrentHospital().deptName  }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">就诊科室</text>
          <text class="info-value">{{ appointmentDetails.department }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">医生姓名</text>
          <text class="info-value">{{ appointmentDetails.doctorName }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">就诊时间</text>
          <text class="info-value">{{ appointmentDetails.date }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">就诊时段</text>
          <text class="info-value">{{ appointmentDetails.timeSlot }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">诊号</text>
          <text class="info-value">{{ appointmentDetails.number }}</text>
        </view>
        <view class="info-item">
          <text class="info-label">金额</text>
          <text class="info-value price">{{ appointmentDetails.fee }}元</text>
        </view>
        <view class="info-item">
          <text class="info-label">就诊地点</text>
          <text class="info-value">{{ medicalStore.getCurrentHospital().deptName }}</text>
        </view>
        <!-- <view class="info-item">
          <text class="info-label">医院地址</text>
          <text class="info-value address">{{ appointmentDetails.address }}</text>
        </view> -->
        <view class="info-item">
          <text class="info-label">预约渠道</text>
          <text class="info-value">{{ appointmentDetails.channel }}</text>
        </view>
      </view>
    </view>

    <!-- 底部按钮 -->
    <view class="bottom-actions">
      <van-button 
        class="cancel-btn" 
        plain 
        type="default"
        @click="cancelAppointment"
      >
        取消预约
      </van-button>
      <van-button 
        class="pay-btn" 
        type="info"
        @click="goPay"
      >
        去支付
      </van-button>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { onLoad, onUnload, onHide } from '@dcloudio/uni-app'
import { useMedicalStore } from '@/stores/modules/medical'
import { cancelAppointment as cancelAppointmentApi } from '@/api/appointment'
import { useUserStore } from '@/stores'
const userStore = useUserStore()
// Store实例
const medicalStore = useMedicalStore()

// 页面参数
const orderNo = ref('')
const appointmentId = ref('')

// 取消预约需要的参数
const cancelParams = ref({
  id: "0",           // 预约单id
  staffId: 0,      // 医生id
  patientId: 1,    // 患者id（暂时固定为1）
  userId: userStore.userInfo.userId,       // 用户id（暂时固定为2）
  clnicId: 0,      // 医生坐诊id
  slotNo: 0        // 号
})

// 倒计时相关
const remainingTime = ref(1 * 60) // 1分钟倒计时
let timer: number | null = null

// 清理定时器的函数
const clearCountdownTimer = () => {
  if (timer) {
    clearInterval(timer as number)
    timer = null
    console.log('倒计时定时器已清理')
  }
}

// 医院信息
// const hospitalName = ref('四川大学华西医院锦江院区（锦江院区）')

// 预约信息
const appointmentInfo = ref({
  dayNumber: '9',
  fullDate: '08月18日 星期一',
  doctorName: '王铭',
  doctorLevel: '四级专家',
  timeSlot: '上午 08:15-08:45',
  department: '锦江感染科门诊'
})

// 患者信息
const patientInfo = ref({
  name: '芮佳楠',
  gender: '男',
  age: '27',
  phone: '188****5958'
})

// 预约详细信息
const appointmentDetails = ref({
  area: '锦江院区',
  department: '锦江感染科门诊',
  doctorName: '王铭',
  date: '2025-08-18',
  timeSlot: '上午 08:15-08:45',
  number: '9',
  fee: '22',
  location: '锦江院区5号楼感染性疾病中心一楼102诊室',
  address: '成都市锦江区锦江大道1166号',
  channel: '小程序'
})

// 格式化倒计时时间
const formatTime = (seconds: number): string => {
  const hours = Math.floor(seconds / 3600)
  const minutes = Math.floor((seconds % 3600) / 60)
  const secs = seconds % 60
  return `${hours.toString().padStart(2, '0')}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

// 开始倒计时
const startCountdown = () => {
  if (timer) clearInterval(timer)
  
  timer = setInterval(() => {
    if (remainingTime.value > 0) {
      remainingTime.value--
    } else {
      if (timer !== null) {
        clearInterval(timer as number)
        timer = null
      }
      // 倒计时结束，自动取消预约
      (uni as any).showModal({
        title: '支付超时',
        content: '支付时间已到，预约已自动取消',
        showCancel: false,
        success: () => {
          uni.navigateBack()
        }
      })
    }
  }, 1000)
}

// 取消预约
const cancelAppointment = async () => {
  const confirmed = await (uni as any).showModal({
    title: '确认取消',
    content: '确定要取消此次预约吗？',
    confirmText: '确认取消',
    cancelText: '继续支付'
  })

  if (confirmed.confirm) {
    try {
      // 显示加载状态
      (uni as any).showLoading({
        title: '取消中...'
      })

      // 调用取消预约API（使用 uni.request 包装为 Promise）
      // console.log('发送取消预约请求，参数:', cancelParams.value)
      
      const response = await cancelAppointmentApi({
        id: cancelParams.value.id,
        staffId: cancelParams.value.staffId,
        patientId: cancelParams.value.patientId,
        userId: cancelParams.value.userId,
        clnicId: cancelParams.value.clnicId,
        slotNo: cancelParams.value.slotNo
      })
      // console.log('取消预约API返回:', response)

      // 隐藏加载状态
      ;(uni as any).hideLoading()

      if (response && response.code == 200) {
        console.log('请求返回预约成功')
        // 清除定时器
        if (timer) {
          clearInterval(timer)
          timer = null
        }

        // 先获取预约信息（在清除之前）
        const appointment = medicalStore.getCurrentAppointment()
        
        // 显示成功提示
        uni.showToast({
          title: '预约已取消',
          icon: 'success'
        })

        // 清除当前预约信息
        medicalStore.clearCurrentAppointment()

        // 延迟跳转到选择医生界面
        setTimeout(() => {
            
          // @ts-ignore
          (uni as any).reLaunch({
            url: `/pages/appointment/doctor-select?departmentId=${appointment?.departmentId || '26'}&departmentName=${appointment?.department || '内科'}`
          })
        }, 1500)
     
      } else {
        uni.showToast({
          title: response.msg || '取消失败，请重试',
          icon: 'none'
        })
      }
    } catch (error) {
      // 隐藏加载状态
      (uni as any).hideLoading()
      
      console.error('取消预约异常:', error)
      console.error('错误详情:', JSON.stringify(error))
      
      uni.showToast({
        title: '取消失败，请重试',
        icon: 'none'
      })
    }
  }
}

// 去支付
const goPay = () => {
  uni.navigateTo({
    url: `/pages/appointment/payment?orderNo=${orderNo.value}&doctorName=${appointmentDetails.value.doctorName}&departmentName=${appointmentDetails.value.department}&date=${appointmentDetails.value.date}&time=${appointmentDetails.value.timeSlot}&fee=${appointmentDetails.value.fee}`
  })
}

// 页面加载
// 页面加载
onLoad((options: Record<string, string>) => {
  console.log('待支付页面 onLoad', options)
  
  // 基础参数（从URL获取）
  if (options.orderNo) {
    orderNo.value = options.orderNo
  }
  
  if (options.appointmentId) {
    appointmentId.value = options.appointmentId
  }

  // 主要从store获取数据更新页面显示
  const currentAppointment = medicalStore.getCurrentAppointment()
  if (currentAppointment) {
    console.log('从store获取预约信息:', currentAppointment)
    
    // 更新订单号（如果URL没有的话）
    if (!orderNo.value && currentAppointment.orderNo) {
      orderNo.value = currentAppointment.orderNo
    }
    if (!appointmentId.value && currentAppointment.appointmentId) {
      appointmentId.value = currentAppointment.appointmentId
    }
    
    // 更新预约信息卡片
    if (currentAppointment.slotNo) {
      appointmentInfo.value.dayNumber = currentAppointment.slotNo.toString()
    }
    
    // 格式化日期显示
    if (currentAppointment.date) {
      const dateObj = new Date(currentAppointment.date)
      const formattedDate = `${String(dateObj.getMonth() + 1).padStart(2, '0')}月${String(dateObj.getDate()).padStart(2, '0')}日 ${['周日', '周一', '周二', '周三', '周四', '周五', '周六'][dateObj.getDay()]}`
      appointmentInfo.value.fullDate = formattedDate
    }
    
    appointmentInfo.value.doctorName = currentAppointment.doctorName
    appointmentInfo.value.doctorLevel = '四级专家' // 可以从其他地方获取
    appointmentInfo.value.timeSlot = currentAppointment.time
    appointmentInfo.value.department = currentAppointment.department
    
    // 更新详细信息
    appointmentDetails.value.department = currentAppointment.department
    appointmentDetails.value.doctorName = currentAppointment.doctorName
    appointmentDetails.value.date = currentAppointment.date
    appointmentDetails.value.timeSlot = currentAppointment.time
    appointmentDetails.value.fee = currentAppointment.fee.toString()
    if (currentAppointment.slotNo) {
      appointmentDetails.value.number = currentAppointment.slotNo.toString()
    }
  } else {
    console.log('store中没有预约数据，尝试从URL参数获取')
    // 兜底：从URL参数获取（如果store中没有数据）
    if (options.slotNo) {
      appointmentInfo.value.dayNumber = options.slotNo
      appointmentDetails.value.number = options.slotNo
    }
    
    if (options.doctorName) {
      appointmentInfo.value.doctorName = decodeURIComponent(options.doctorName)
      appointmentDetails.value.doctorName = decodeURIComponent(options.doctorName)
    }
    
    if (options.timeSlot) {
      appointmentInfo.value.timeSlot = decodeURIComponent(options.timeSlot)
      appointmentDetails.value.timeSlot = decodeURIComponent(options.timeSlot)
    }
    
    if (options.department) {
      appointmentInfo.value.department = decodeURIComponent(options.department)
      appointmentDetails.value.department = decodeURIComponent(options.department)
    }
    
    if (options.date) {
      appointmentDetails.value.date = options.date
    }
    
    if (options.fee) {
      appointmentDetails.value.fee = options.fee
    }
  }
  
  // 从医疗store获取当前就诊卡信息作为补充
  const currentCard = medicalStore.getCurrentMedicalCard()
  if (currentCard) {
    patientInfo.value.name = currentCard.patientName
    // 可以根据需要更新其他患者信息
    // patientInfo.value.phone = currentCard.phone
    // patientInfo.value.gender = currentCard.gender
    // patientInfo.value.age = currentCard.age
  }

  // 设置取消预约参数（复用之前获取的currentAppointment）
  if (currentAppointment) {
    // 从 store 中获取所有取消预约需要的参数
    cancelParams.value.id =  appointmentId.value
    cancelParams.value.staffId = parseInt(currentAppointment.doctorId)
    cancelParams.value.clnicId = currentAppointment.clnicId || parseInt(options.clnicId || '0')
    cancelParams.value.slotNo = currentAppointment.slotNo || parseInt(options.slotNo || '0')
    
    console.log('从store获取取消预约参数成功')
  } else {
    // 如果 store 中没有数据，从 URL 参数获取（兜底方案）
    console.log('store中没有预约数据，使用URL参数作为兜底')
    if (options.appointmentId) {
      cancelParams.value.id = options.appointmentId
    }
    if (options.doctorId) {
      cancelParams.value.staffId = parseInt(options.doctorId)
    }
    if (options.clnicId) {
      cancelParams.value.clnicId = parseInt(options.clnicId)
    }
    if (options.slotNo) {
      cancelParams.value.slotNo = parseInt(options.slotNo)
    }
  }

  console.log('取消预约参数:', cancelParams.value)
  
  // 开始倒计时
  startCountdown()
})

onMounted(() => {
  // 页面挂载后的逻辑
})

// 页面隐藏时清理定时器（用户切换到其他页面）
onHide(() => {
  console.log('页面隐藏，清理定时器')
  clearCountdownTimer()
})

// 页面卸载时清理定时器（页面销毁）
onUnload(() => {
  console.log('页面卸载，清理定时器')
  clearCountdownTimer()
})

// Vue3生命周期钩子 - 组件卸载前清理
onBeforeUnmount(() => {
  console.log('组件卸载前，清理定时器')
  clearCountdownTimer()
})

</script>

<style lang="scss" scoped>
.container {
  background-color: #f8f9fa;
  min-height: 100vh;
  padding-bottom: 120rpx;
}

.status-header {
  background: white;
  padding: 32rpx 24rpx;
  margin-bottom: 16rpx;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
  margin-bottom: 16rpx;
}

.status-icon {
  width: 48rpx;
  height: 48rpx;
  background: #fff5e6;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
}

.status-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #323233;
}

.countdown {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.countdown-label {
  font-size: 28rpx;
  color: #969799;
}

.countdown-time {
  font-size: 28rpx;
  color: #ff8c00;
  font-weight: 500;
}

.hospital-header {
  background: white;
  padding: 24rpx;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.hospital-logo {
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  overflow: hidden;
}

.logo-image {
  width: 100%;
  height: 100%;
}

.hospital-name {
  flex: 1;
  font-size: 32rpx;
  color: #323233;
  font-weight: 500;
}

.appointment-card {
  background: white;
  margin: 0 24rpx 16rpx;
  border-radius: 16rpx;
  padding: 32rpx;
}

.appointment-main {
  display: flex;
  gap: 32rpx;
}

.date-section {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 16rpx;
  background: #fff5e6;
  border-radius: 12rpx;
  border: 2rpx solid #ff8c00;
  min-width: 120rpx;
}

.date-number {
  font-size: 48rpx;
  font-weight: bold;
  color: #ff8c00;
  line-height: 1;
}

.date-text {
  margin-top: 8rpx;
}

.date-label {
  font-size: 24rpx;
  color: #ff8c00;
}

.appointment-details {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.appointment-date {
  font-size: 32rpx;
  font-weight: bold;
  color: #323233;
}

.doctor-info {
  display: flex;
  align-items: center;
  gap: 16rpx;
}

.doctor-name {
  font-size: 28rpx;
  color: #323233;
  font-weight: 500;
}

.doctor-level {
  font-size: 24rpx;
  color: #969799;
}

.time-slot, .department {
  font-size: 28rpx;
  color: #646566;
}

.patient-section {
  background: white;
  padding: 24rpx;
  margin-bottom: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.patient-info {
  display: flex;
  align-items: center;
  gap: 24rpx;
}

.patient-avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  overflow: hidden;
  background: #f0f8ff;
}

.avatar-image {
  width: 100%;
  height: 100%;
}

.patient-details {
  display: flex;
  flex-direction: column;
  gap: 8rpx;
}

.patient-name {
  font-size: 32rpx;
  color: #323233;
  font-weight: 500;
}

.patient-basic {
  font-size: 28rpx;
  color: #969799;
}

.qr-code {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.info-section {
  background: white;
  margin: 0 24rpx;
  border-radius: 16rpx;
  padding: 32rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #323233;
  margin-bottom: 24rpx;
}

.info-list {
  display: flex;
  flex-direction: column;
  gap: 24rpx;
}

.info-item {
  display: flex;
  align-items: flex-start;
  justify-content: space-between;
  gap: 24rpx;
}

.info-label {
  font-size: 28rpx;
  color: #969799;
  min-width: 140rpx;
  flex-shrink: 0;
}

.info-value {
  font-size: 28rpx;
  color: #323233;
  text-align: right;
  flex: 1;
  
  &.price {
    color: #ee0a24;
    font-weight: 500;
  }
  
  &.address {
    color: #07c160;
  }
}

.bottom-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: white;
  padding: 24rpx;
  display: flex;
  gap: 24rpx;
  box-shadow: 0 -2rpx 12rpx rgba(0, 0, 0, 0.1);
}

.cancel-btn {
  flex: 1;
  height: 88rpx;
  border-color: #ebedf0;
  color: #646566;
}

.pay-btn {
  flex: 2;
  height: 88rpx;
  background: #07c160;
  border-color: #07c160;
}
</style>
